package sk.bielyvlk.vlkgps;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import sk.bielyvlk.vlkgps.db.DbHelper;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemLongClickListener;

public class TracksList extends ListActivity implements ServiceConnection, OnItemLongClickListener {
	public static final String TAG = "vlkGPS.TracksList";

	VlkGpsService vlkGpsService = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onStart");

		try {
			Intent serviceIntent = new Intent(TracksList.this, VlkGpsService.class);
			bindService(serviceIntent, this, 0);
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		getListView().setOnItemLongClickListener(this);
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d(TAG, "onStart");
	}

	@Override
	public void onRestart() {
		super.onRestart();
		Log.d(TAG, "onRestart");
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "onPause");
	}

	@Override
	public void onStop() {
		super.onStop();
		Log.d(TAG, "onStop");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		Log.d(TAG, "onServiceConnected");
		try {
			vlkGpsService = ((VlkGpsService.LocalBinder) service).getService();
			DbHelper dbHelper = vlkGpsService.getDbHelper();
			Cursor c = dbHelper.getTracksList();
			String[] from = new String[] { "name", "name", };
			int[] to = new int[] { R.id.text1, R.id.text2, };
			SimpleCursorAdapter tracks = new SimpleCursorAdapter(this, R.layout.track_row, c, from, to);
			setListAdapter(tracks);
		} catch (Exception e) {
			Log.d(TAG, e.toString());
		}
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		Log.d(TAG, "onServiceDisconnected");
		vlkGpsService = null;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.d(TAG, "item clicked: " + id);
	}

	private void exportTrack(long id) {
		DbHelper dbHelper = vlkGpsService.getDbHelper();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		String name = dbHelper.getTrackName(id);
		try {
			FileWriter file = new FileWriter("/sdcard/vlkgps/" + name + ".gpx");
			file.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
			file.write("<gpx version=\"1.1\" creator=\"vlkGPS - http://vlkgps.bielyvlk.sk\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/1\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\r\n");
			file.write("  <trk>\r\n");
			file.write("    <name>" + name + "</name>\r\n");
			file.write("    <trkseg>\r\n");
			Cursor c = db.rawQuery("SELECT lon, lat, alt, spd, acc, time FROM trackpoints WHERE track_id = " + id + " ORDER BY _id;", null);
			Log.d(TAG, "track points: " + c.getCount());
			c.moveToFirst();
			do {
				SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
				formater.setTimeZone(TimeZone.getTimeZone("GMT"));
				String time = formater.format(new Date(c.getLong(5)));
				double lon = c.getLong(0) / DbHelper.DB_DEGREES_MULT;
				double lat = c.getLong(1) / DbHelper.DB_DEGREES_MULT;
				double alt = c.getLong(2) / DbHelper.DB_METERS_MULT;
				double spd = c.getLong(3) / DbHelper.DB_METERS_MULT;
				double acc = c.getLong(4) / DbHelper.DB_METERS_MULT;
				file.write("      <trkpt lon=\"" + lon + "\" lat=\"" + lat + "\">\r\n");
				file.write("        <ele>" + alt + "</ele>\r\n");
				file.write("        <speed>" + spd + "</speed>\r\n");
				file.write("        <time>" + time + "</time>\r\n");
				file.write("        <extensions>\r\n");
				file.write("          <accuracy>" + acc + "</accuracy>\r\n");
				file.write("        </extensions>\r\n");
				file.write("      </trkpt>\r\n");
			} while (c.moveToNext());
			file.write("    </trkseg>\r\n");
			file.write("  </trk>\r\n");
			file.write("</gpx>\r\n");
			file.close();
			c.close();
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
	}

	private long selectedTrackId = 0;
	//private View selectedView = null;

	@Override
	public boolean onItemLongClick(AdapterView<?> l, View v, int position, long id) {
		DbHelper dbHelper = vlkGpsService.getDbHelper();
		selectedTrackId = id;
		//selectedView = v;
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(dbHelper.getTrackName(selectedTrackId));
			builder.setItems(R.array.trackSubmenu, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface d, int id) {
					Log.d(TAG, "submenu clicked: " + id + " trackId: " + selectedTrackId);
					/* TODO don't use numbers */
					switch (id) {
						case 2: /* export */
							exportTrack(selectedTrackId);
							break;
						case 3: /* delete */
							try {
								DbHelper dbHelper = vlkGpsService.getDbHelper();
								dbHelper.deleteTrack(selectedTrackId);
								finish();
							} catch (Exception e) {
								Log.e(TAG, e.toString());
							}
							break;
					}
				}
			});
			builder.create().show();
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		return true;
	}

}
